package ar.edu.utn.frsf.tpae.a2012.g02.dao.implementacion;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import ar.edu.utn.frsf.tpae.a2012.g02.dao.GenericDAO;
import ar.edu.utn.frsf.tpae.a2012.g02.models.Cliente;

public class GenericHibernateDAO<E> implements GenericDAO<E> {

	private SessionFactory sessionFactory = new AnnotationConfiguration()
			.configure().buildSessionFactory();

	@Override
	public E saveOrUpdate(E entity) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.saveOrUpdate(entity);
		session.getTransaction().commit();
		session.close();
		return entity;
	}

	@Override
	public boolean delete(E entity) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(entity);
		session.getTransaction().commit();
		session.close();
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getAll() {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from " + Cliente.class.getName());
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public E getById(int id) {
		Session session = sessionFactory.openSession();
		return (E) session.get(getEntityClass(), id);
	}

	@SuppressWarnings("unchecked")
	private Class<E> getEntityClass() {
		ParameterizedType ptype = (ParameterizedType) getClass()
				.getGenericSuperclass();
		return (Class<E>) ptype.getActualTypeArguments()[0];
	}
}
